package com.dingyuhang.controller;

import com.dingyuhang.bean.Forum;
import com.dingyuhang.bean.Topic;
import com.dingyuhang.bean.User;
import com.dingyuhang.service.ForumService;
import com.dingyuhang.service.TopicService;

import com.dingyuhang.util.MyAnn;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

/**
 * 帖子
 */
@Controller
public class TopicController {
	
	@Autowired
	private TopicService topicService;
	
	@Autowired
	private ForumService forumService;
	/**
	 * 跳发布帖子页面
	 * @param model
	 * @return
	 */
	@GetMapping("/my/publishTopic")
	public String toPublishTopic(Topic topic, Model model) {
		model.addAttribute("topic", topic);//页面绑定对象
		model.addAttribute("forums", forumService.selectForums());//页面版块的下拉查询
		return "my/topics_pulish";
	}
	
	/**
	 * 发布帖子
	 * @param model
	 * @param topic
	 * @param session
	 * @return
	 */
	@MyAnn("add")
	@PostMapping("/my/publishTopic")
	public String publishTopic(Model model,@Valid @ModelAttribute("topic")Topic topic,BindingResult result,  HttpSession session) {
       if(result.hasErrors()) {
    	   model.addAttribute("forums", forumService.selectForums());//页面版块的下拉查询
    	   return "my/topics_pulish";
       }
		User user = (User) session.getAttribute("LOGIN_USER");//从session获取获取到登陆人的信息   因为添加帖子表的时候表字段中有发帖人的id
		topicService.publishTopic(topic,user);//发布帖子
		return "redirect:/index";
	}
	
	
	/**
	 * 我的贴子
	 */
	@MyAnn("/my/topics")
	 @GetMapping("/my/topics")
	    public String myTopic(Model model, HttpSession session){
	        User user = (User) session.getAttribute("LOGIN_USER");
	        List<Topic> topics = topicService.getMyTopics(user);
	        model.addAttribute("topics", topics);
	        return "my/topics_list";
	    }
	 
	 
	 /**
	  * 点击贴子id查询贴子的信息及回复
	  */
	 @RequestMapping("/my/topicRelpy")
	 public String topicRelpy(Integer id,Model model) {
		 Topic topic = topicService.topicRelpy(id); //查询贴子及回复的内容
		 model.addAttribute("topic", topic);
		 return "topic_reply";
	 }
  
	 
	 /**
	  * 根据版块查询帖子
	  */
	 @GetMapping("/forum/topics")
	 public String selectTopicsByForumId(Forum forum, @RequestParam(defaultValue="1")Integer pageNum, Model model) {
		PageInfo<Topic>  pageInfo = topicService.selectTopicsByForumId(forum.getId(),pageNum);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("forum", forum);
		return "forum_topics";
	 }
}
